package com.xyhuo.leetcode.january;

import com.xyhuo.leetcode.common.ListNode;

import java.util.HashSet;
import java.util.Set;

/**
 * 相交链表
 * https://leetcode.cn/problems/intersection-of-two-linked-lists/
 *
 * @time 2024/1/23
 */
public class GetIntersectionNode {

    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        Set<ListNode> allNodes = getAllNodes(headA);
        ListNode node = headB;
        while (node != null) {
            if (allNodes.contains(node)) {
                return node;
            }
            node = node.next;
        }
        return null;
    }

    private Set<ListNode> getAllNodes(ListNode head) {
        ListNode node = head;
        Set<ListNode> set = new HashSet<>();
        while (node != null) {
            set.add(node);
            node = node.next;
        }
        return set;
    }
}
